"""
统一错误处理模块
提供标准化的API错误响应和异常处理机制
"""

from typing import Optional, Dict, Any
from fastapi import HTTPException, status
from fastapi.responses import JSONResponse
from src.utils.logging import get_logger
from src.exceptions import ResearchException

logger = get_logger(__name__)


class APIError:
    """API错误响应模型"""
    
    def __init__(self, 
                 code: str, 
                 message: str, 
                 status_code: int = status.HTTP_500_INTERNAL_SERVER_ERROR,
                 details: Optional[Dict[str, Any]] = None):
        self.code = code
        self.message = message
        self.status_code = status_code
        self.details = details or {}

    def to_dict(self) -> dict:
        """转换为字典格式"""
        return {
            "error": {
                "code": self.code,
                "message": self.message,
                "status_code": self.status_code,
                "details": self.details
            }
        }


def create_error_response(error: APIError) -> JSONResponse:
    """创建标准化的错误响应"""
    return JSONResponse(
        status_code=error.status_code,
        content=error.to_dict()
    )


def handle_research_exception(exc: ResearchException) -> JSONResponse:
    """处理ResearchException异常"""
    error_map = {
        "SESSION_NOT_FOUND": status.HTTP_404_NOT_FOUND,
        "VALIDATION_ERROR": status.HTTP_400_BAD_REQUEST,
        "WORKFLOW_ERROR": status.HTTP_500_INTERNAL_SERVER_ERROR,
        "CONFIGURATION_ERROR": status.HTTP_500_INTERNAL_SERVER_ERROR,
        "RATE_LIMIT_EXCEEDED": status.HTTP_429_TOO_MANY_REQUESTS,
        "SERVICE_UNAVAILABLE": status.HTTP_503_SERVICE_UNAVAILABLE,
        "DATABASE_ERROR": status.HTTP_500_INTERNAL_SERVER_ERROR,
    }
    
    status_code = error_map.get(exc.code, status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    error = APIError(
        code=exc.code,
        message=exc.message,
        status_code=status_code,
        details=getattr(exc, '__dict__', {})
    )
    
    logger.error(f"ResearchException: {exc.message}", extra=error.to_dict())
    return create_error_response(error)


def handle_http_exception(exc: HTTPException) -> JSONResponse:
    """处理HTTPException异常"""
    error = APIError(
        code="HTTP_ERROR",
        message=exc.detail,
        status_code=exc.status_code,
        details={
            "headers": exc.headers
        } if exc.headers else {}
    )
    
    logger.error(f"HTTPException: {exc.detail}", extra=error.to_dict())
    return create_error_response(error)


def handle_generic_exception(exc: Exception) -> JSONResponse:
    """处理通用异常"""
    error = APIError(
        code="INTERNAL_ERROR",
        message="内部服务器错误",
        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
        details={
            "exception_type": type(exc).__name__,
            "exception_message": str(exc)
        }
    )
    
    logger.error(f"GenericException: {str(exc)}", extra=error.to_dict(), exc_info=True)
    return create_error_response(error)


def api_error_handler(exc: Exception) -> JSONResponse:
    """
    统一API错误处理器
    根据异常类型返回相应的错误响应
    """
    if isinstance(exc, ResearchException):
        return handle_research_exception(exc)
    elif isinstance(exc, HTTPException):
        return handle_http_exception(exc)
    else:
        return handle_generic_exception(exc)